<?php
/**
 * Description: 申论套题作业模块
 * User: devforma
 * Date: 16/7/26
 * Time: 12:05
 */

require __DIR__ . '/ProcessExerciseBase.class.php';

class ShenlunMultiModule extends ProcessExerciseBase {

    /**
     * 设置作业类型
     */
    protected function setExerciseType() {
        $this->data['exercise_type'] = 10;
    }

    /**
     * 设置作业题目
     */
    protected function setExerciseQuestion() {
        global $cmsdb;

        $this->data['question'] = [];

        //获取题目和材料
        $materialInfo = $cmsdb->getRow('SELECT `id`, `notice`, `information` FROM `original_ztk_shenlun_questions` WHERE `id`=:id', [':id' => $this->questionIds[0]]);
        $questionInfo = (array)$cmsdb->getResults('SELECT `id`, `question`, `answer`, `parent` FROM `original_ztk_shenlun_questions` WHERE `parent`=:id', [':id' => $this->questionIds[0]]);

        $this->data['question'] = array(
            'shenlun_id' => (int)$materialInfo->id,
            'notice'     => $materialInfo->notice,
            'material'   => $materialInfo->information,
            'questions'  => []
        );

        foreach ($questionInfo as $q) {

            $this->data['question']['questions'][] = [
                'question_id' => (int)$q->id,
                'question'    => $q->question,
                'answer'      => $q->answer,
                'status'      => $this->_getHistoryPrimaryQuestionReview($q->id),
            ];
        }

        $this->data['cost_time'] = $this->_getHistoryUserPrimaryExerciseCostTime();
    }

    /**
     * 设置提交权限
     */
    protected function setSubmitPriv() {
        parent::setSubmitPriv();
    }

    /**
     * 设置用户答案
     */
    protected function setUserAnswer() {
        global $uddb;

        //查询用户做题记录
        $sql = 'SELECT * FROM `history_primary_question_review` WHERE `user_id`=:uid AND `exercise_id`=:eid';
        $questionRecords = $uddb->getResults($sql, [':uid' => $this->userId, ':eid' => $this->exerciseId]);

        if (!empty($questionRecords)) { //有用户答题记录
            $userAnswers = [];
            foreach ($questionRecords as $qr) {
                $userAnswers[$qr->question_id] = array(
                    'origin' => [
                        'submit_time' => $qr->action_time,
                        'images'      => explode('#', $qr->user_answer)
                    ],
                    'status' => (int)$qr->status,
                    'status_text' => VipUtils::getStatusText($qr->status)
                );

                //批改信息
                if (!empty($qr->reviewer_id)) {
                    $userAnswers[$qr->question_id]['review'] = [
                        'lector'        => $this->getLectorInfo($qr->reviewer_id),
                        'review_time'   => $qr->review_time,
                        'images'        => explode('#', $qr->review_content),
                        'review_postil' => (string)$qr->review_postil,
                        'score'         => (int)$qr->review_score
                    ];
                }
                //收藏状态
                $userAnswers[$qr->question_id]['is_collected'] = (int)$qr->is_collected;
            }

            //合并题目-用户答案
            foreach ($this->data['question']['questions'] as &$q) {
                $q['user_answer'] = $userAnswers[$q['question_id']];
            }
        }
    }

    /**
     * 检测提交的参数
     * @param array $args 参数
     * @return bool
     */
    public function validateArgs($args) {
        if (!empty($args['answer_content']) && ($args['answer_content'] = json_decode($args['answer_content']))) {
            $this->submitArgs = $args;
            return true;
        }

        return false;
    }

    /**
     * 提交 - 设置作业状态
     */
    protected function setSubmitStatus() {

        $status = $this->_allSmallQuestionsHaveBeenSubmit();

        if ($status == 1) {

            if ($this->exerciseInfo->end_time > $this->now)
                $this->submitExerciseRecord['status'] = 3; //已提交
            else
                $this->submitExerciseRecord['status'] = 5; //过期完成

        } else if ($status == 4) {
            $this->submitExerciseRecord['status'] = 4;
        }
    }

    /**
     * 提交 - 保存答题记录及设置作业统计信息
     */
    protected function saveQuestionRecordsAndSetSubmitSummary() {
        global $uddb;

        $answer = $this->submitArgs['answer_content'];
        //构造题目记录
        $questionRecord = array(
            'question_id'   => $answer->question_id,
            'exercise_id'   => $this->exerciseId,
            'user_id'       => $this->userId,
            'action_time'   => $this->now,
            'user_answer'   => $answer->image_url,
            'reviewer_type' => 0,
            'status'        => 1
        );

        //查询是否存在提交记录
        $sql = 'SELECT `id` FROM `history_primary_question_review` WHERE `user_id`=:uid AND `exercise_id`=:eid AND `question_id`=:qid LIMIT 1';
        $exists = $uddb->getVar($sql, [':uid' => $this->userId, ':eid' => $this->exerciseId, ':qid' => $answer->question_id]);

        if ($exists) {
            $uddb->update('history_primary_question_review', $questionRecord, array('id' => $exists));
        } else {
            $uddb->insert('history_primary_question_review', $questionRecord);
        }

        $oldCostTime = $this->_getHistoryUserPrimaryExerciseCostTime();
        $this->submitExerciseRecord['summary'] = json_encode(['duration' => $answer->cost_time + $oldCostTime]);
    }

    /**
     * 检测小题是否全部为已提交状态
     *
     * @return bool
     */
    private function _allSmallQuestionsHaveBeenSubmit() {
        global $uddb;

        $sql = 'SELECT `id`,`status` FROM `history_primary_question_review` WHERE `user_id`=:uid AND `exercise_id`=:eid ';
        $res = $uddb->getResults($sql, [':uid' => $this->userId, ':eid' => $this->exerciseId]);

        if (!empty($res)) {

            $questionCount = $this->_getSmallQuestionsCount();

            if(count($res) < $questionCount - 1) return 0;//未完成

            $n = 0;

            foreach ($res as $k => $v) {

                if ($v->status == 4)
                    $n++;
            }
            if ($n > 1)
                return 4;//已驳回

            return 1;//待批改
        }

        return 0;//未完成
    }

    /**
     * 获取当前作业下的小题总数
     *
     * @return int|null|string
     */
    private function _getSmallQuestionsCount() {
        global $cmsdb;

        $questionId = $cmsdb->getVar("SELECT question_id FROM `relation_primary_exercise_question` WHERE `primary_exercise_id`=:id", [':id' => $this->exerciseId]);

        if (!empty($questionId))
            return $cmsdb->getVar("SELECT count(id) FROM `original_ztk_shenlun_questions` WHERE `parent`=:id", [':id' => $questionId]);
        else
            return 0;
    }

    /**
     * 获取对应题目的状态
     *
     * @param $questionId
     * @return null|string
     */
    private function _getHistoryPrimaryQuestionReview($questionId) {
        global $uddb;

        $sql = 'SELECT status FROM `history_primary_question_review` WHERE `user_id`=:uid AND `exercise_id`=:eid AND `question_id`=:questionId';
        $status = $uddb->getVar($sql,
            [
                ':uid' => $this->userId,
                ':eid' => $this->exerciseId,
                ':questionId' => $questionId
            ]);
        return !empty($status) ? $status : 0;
    }

    /**
     * 获取作业实际用时
     *
     * @return int|null|string
     */
    private function _getHistoryUserPrimaryExerciseCostTime() {
        $exerciseData = VipUtils::getHistoryUserPrimaryExerciseInfo($this->exerciseId,$this->userId);
        $summary = json_decode($exerciseData->summary,true);

        return !empty($summary['duration']) ? intval($summary['duration']) : 0;
    }

    /**
     * 获取教师信息
     *
     * @param int $letorId 教师id
     * @return array
     */
    private function getLectorInfo($letorId) {
        global $cmsdb;

        $cacheKey = 'vip:func:getLectorInfo:'.$letorId;
        if (($lectorInfo = cacheGet($cacheKey)) == null) {
            $res = $cmsdb->getRow('SELECT `name`, `avatar` FROM `data_teacher` WHERE `id`=:id', array(':id' => $letorId));
            $lectorInfo = array(
                'id'     => (int)$letorId,
                'name'   => $res->name,
                'avatar' => (string)$res->avatar
            );

            cacheAdd($cacheKey, $lectorInfo, 24*60*60);
        }

        return $lectorInfo;
    }
}